package br.com.nooclix.ptt.ws.application;

import java.util.Date;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import br.com.nooclix.ptt.core.application.MembershipApplication;
import br.com.nooclix.ptt.core.domain.member.Membership;
import br.com.nooclix.ptt.core.domain.member.MembershipStatus;
import br.com.nooclix.ptt.core.infrastructure.util.ApplicationContextRegisterCore;
import br.com.nooclix.ptt.core.infrastructure.util.ResponseData;
import br.com.nooclix.ptt.ws.adapter.Adapter;
import br.com.nooclix.ptt.ws.adapter.impl.MembershipAdapter;
import br.com.nooclix.ptt.ws.utilities.Utilities;

@Path("/membership")
public class MembershipRestApplication {

	private MembershipApplication membershipApplication;
	private Adapter<Membership> adapter;

	public MembershipRestApplication() {
		super();
		membershipApplication = ApplicationContextRegisterCore.getBean(
				"membershipApplication", MembershipApplication.class);
		adapter = new MembershipAdapter();
	}

	@GET
	@Path("/find/criterion/{name}/{startStringDate}/{endStringDate}/{status}/{offset}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response findByCriterion(@PathParam("name") String name,
			@PathParam("startStringDate") String startStringDate,
			@PathParam("endStringDate") String endStringDate,
			@PathParam("status") String status, @PathParam("offset") int offset) {

		if (name.equalsIgnoreCase("null")) {
			name = "";
		}
		Date startDate = Utilities.getDateFromString(startStringDate);
		Date endDate = Utilities.getDateFromString(endStringDate);
		ResponseData<Membership> responseData = membershipApplication
				.findByCriterion(name, startDate, endDate,
						MembershipStatus.fromString(status), offset);

		String json = adapter.convert(responseData);
		return Response.ok(json).build();
	}

	@GET
	@Path("/find/active/nospace/{name}/{offset}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response findActiveMembershipWithoutSpaceByName(
			@PathParam("name") String name, @PathParam("offset") int offset) {
		Response response = null;
		if (name.equalsIgnoreCase("null")){
			name = null;
		}
		List<Membership> list = membershipApplication
				.findActiveMembershipWithoutSpaceByName(name, offset);
		String json = adapter.convert(list);
		response = Response.ok(json).build();
		return response;
	}

	public static void main(String[] args) {
		System.out
				.println(new MembershipRestApplication()
						.findActiveMembershipWithoutSpaceByName("teste", 0)
						.getEntity());
	}
}
